package com.cctc.mychat.server.handler.Message;

import com.cctc.mychat.common.protocol.message.impl.request.LogoutRequestMessage;
import com.cctc.mychat.common.protocol.message.impl.response.LogoutResponseMessage;
import com.cctc.mychat.common.session.SessionManager;
import com.cctc.mychat.common.util.JsonUtils;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class LogoutRequestMessageHandler extends SimpleChannelInboundHandler<LogoutRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LogoutRequestMessage request) throws Exception {
        System.out.println("[LogoutRequestMessageHandler] 注销消息：" + JsonUtils.toJson(request));

        LogoutResponseMessage response = LogoutResponseMessage.builder().build();
        Channel userChannel = ctx.channel();
        if (SessionManager.hasLogin(userChannel)) {
            SessionManager.unBindSession(userChannel);
            response.setSuccess(true);
            System.out.println("[LogoutRequestMessageHandler] 注销成功！！！");
        } else {
            response.setSuccess(false);
            String reason = "用户不存在（已注销）！！！";
            response.setReason(reason);
            System.err.println("[LogoutRequestMessageHandler] 注销失败，原因：" + reason);
        }
        ctx.writeAndFlush(response);
    }
}
